package com.kly.user.task;

import cn.hutool.core.net.NetUtil;
import com.alibaba.nacos.api.config.annotation.NacosValue;
import com.fqgj.log.factory.LogFactory;
import com.fqgj.log.interfaces.Log;
import com.kly.user.task.enums.TaskTypeEnum;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;

/**
 * 支付回调任务
 * @author linqu
 */
@Component
public class UserScheduledTasks {
    private static Log logger = LogFactory.getLog(UserScheduledTasks.class);

    @Resource
    UserTaskExecutor userTaskExecutor;
    /**
     * 固定频率任务
     */
    private static final Integer TASK_PERIOD_FIXED = 1;
    /**
     * 指定时间
     */
    private static final Integer TASK_PERIOD_UNFIXED = 2;

    @NacosValue(value = "${task.job.executor.ip}", autoRefreshed = true)
    private String taskJobExecutor;

    private String localIP = NetUtil.getLocalhostStr();


    /**
     * 上一次执行结束之后30秒再执行
     */
    @Scheduled(fixedDelay = 30000)
    public void execute() {
        if (!taskJobExecutor.contains(localIP)) {
            logger.info("=============NotTaskJobExecutor, currentLocalAddress:{}, onlyExecuteTaskIn:{}", localIP, taskJobExecutor);
            return;
        }
        logger.info("=============UserScheduledTasks.execute Start==================");
        for (TaskTypeEnum taskType : TaskTypeEnum.values()) {
            if (taskType.getTaskPeriod().equals(TASK_PERIOD_FIXED)) {
                userTaskExecutor.executeJob(taskType);
            }
        }
        logger.info("=================UserScheduledTasks.execute End==============");
    }

    /**
     * 每天执行一次，凌晨1点钟执行
     */
    @Scheduled(cron = "0 0 0/1 * * ? ")
    public void execute2() {
        if (!taskJobExecutor.contains(localIP)) {
            logger.info("=============NotTaskJobExecutor, currentLocalAddress:{}, onlyExecuteTaskIn:{}", localIP, taskJobExecutor);
            return;
        }
        logger.info("=============UserScheduledTasks.execute2 Start==================");
        for (TaskTypeEnum taskType : TaskTypeEnum.values()) {
            if (taskType.getTaskPeriod().equals(TASK_PERIOD_UNFIXED)) {
                userTaskExecutor.executeJob(taskType);
            }
        }
        logger.info("=================UserScheduledTasks.execute2 End==============");
    }


}
